import sys
import iview
import config
import utils
import classes

try:
	import xbmc, xbmcgui, xbmcplugin
except ImportError:
	pass # for PC debugging

def play(url):

	pDialog = xbmcgui.DialogProgress()
	pDialog.update(0)
	pDialog.create('iView', 'Getting iView Config')
	iview_config = iview.get_config()


	pDialog.update(20)
	pDialog.create('iView', 'Getting iView Authentication')
	auth = iview.comm.get_auth(iview_config)

	pDialog.update(40)
	pDialog.create('iView', 'Getting Program')
	p = classes.Program()
	p.parse_xbmc_url(url)

	pDialog.update(60)
	pDialog.create('iView', 'Loading Program Information')
	try:
		# Playpath shoud look like this:
		# 	Akamai: mp4:flash/playback/_definst_/itcrowd_10_03_02
		playpath = auth['playpath_prefix'] + p.url
		if playpath.split('.')[-1] == 'mp4':
			playpath = 'mp4:' + playpath
	
		# Strip off the .flv or .mp4
		playpath = playpath.split('.')[0]
	
		# rtmp_url should look like:
		#	rtmp://cp53909.edgefcs.net/
		# and I just add the filename to the end, so XBMC thinks each show is different
		#	rtmp://cp53909.edgefcs.net/ondemanditcrowd_10_03_02.mp4
		url = "%s/%s" % (auth['rtmp_url'], p.url)
	
		# tcurl should look like: 
		#   rtmp://cp53909.edgefcs.net/ondemand?auth=daEafdXclazc5ahcdd.cBd.agbkbIa1dNal-blFh2v-8-onu_sEwpM&aifp=v001
		#tcurl = auth['rtmp_url'] + '?auth=' + auth['token']
		tcurl = "%s?auth=%s" % (auth['rtmp_url'], auth['token'])
				
		# Build the final RTMP Url. New syntax for external librtmp
		# http://trac.xbmc.org/ticket/8971
		rtmp_url = "%s playpath=%s swfurl=%s swfvfy=true" % (url, playpath, config.swf_url)
	
		listitem=xbmcgui.ListItem(label=p.get_list_title(), iconImage=p.thumbnail, thumbnailImage=p.thumbnail)
		listitem.setProperty("PlayPath", playpath)
		listitem.setProperty("TcUrl", tcurl)
		listitem.setInfo('video', p.get_xbmc_list_item())
	
		pDialog.update(80)
		pDialog.create('iView', 'Starting %s' % p.get_list_title())
		xbmc.Player().play(rtmp_url, listitem)

		pDialog.close()

	except:
		# user cancelled dialog or an error occurred
		print "ERROR: %s (%d) - %s" % ( sys.exc_info()[ 2 ].tb_frame.f_code.co_name, sys.exc_info()[ 2 ].tb_lineno, sys.exc_info()[ 1 ], )
